package DriverMannagerText;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 */
public class TextPrepareStatement {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            //1.加载数据库提供的驱动包进行注册
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            connection = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8", "root", "123456");

            //3.定义预编译SQL语句
            System.out.println("请输入学生姓名：");
            Scanner scanner =new Scanner(System.in);
            String name = scanner.next();
            String sql ="select student_id,sn,name,mail,class_id from student where name =?";
            //4.创建Statement
            statement = connection.prepareStatement(sql);
            //用真实值代替占位符
            statement.setString(1,name);
            //5.执行SQL语句，获取查询结果
            resultSet = statement.executeQuery();//执行 select 等查询语句
            //statement.executeUpdate(sql);  //执行 update、insert、delete等更新语句
            //遍历结果集
            while (resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                String stuClassId = resultSet.getString(5);
                System.out.println(MessageFormat.format
                        ("学生编号={0},学号={1},姓名={2},邮件={3},班级编号={4}",stuId,stuSn,stuName,stuMail,stuClassId));

            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //6.依次释放资源，关闭连接
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
